<?php

/**
 * 卡券订单
 */
namespace App\Service\OrderService\OrderInterfaceService;
use App\Service\BaseService;
use App\Model\CommodityModel\CommodityArchives;
use Service\AppService\IdService;
use Service\Code\Normal;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\CommodityModel\WarehouseInfo;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\Order;
use App\Model\PssModel\OrderGoods;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\PssModel\OrderSupplierAmountExtra;
class OrderCoupon extends BaseService
{
    /**
     * 卡券订单
     * @param array $param
     * @return mixed
     */
    public function placeOrder(array $param = [])
    {
        $placeOrderInfo = $param['requestData'];
        $binfo          = $param['binfo'];
        $bid            = $binfo['bid'];
        $goods          = $placeOrderInfo['goods'];
        $goodsSkus      = array_column($goods,'goodsSku');
        
        //获取卡券商品
        $tableName = CommodityArchives::instance()->getTable();
        $list = CommodityArchives::instance()
        ->from("{$tableName} as csb")
        ->select([
            'csb.ID',
            'csb.SKUCode',
            'csb.BarCode',
            'csb.Name',
            'csb.Weight',
            'csb.ThirdClassificationID',
            'cds.Images',
            'u.Name as UnitName',
        ])
        ->leftJoin('commoditydescription_s2b as cds','cds.CommodityInfoID','=','csb.ID')
        ->leftJoin('unitinfo_s2b as u','u.ID','=','csb.UnitID')
        ->whereIn('csb.SKUCode',$goodsSkus)
        ->where('csb.CommodityForm',2)
        ->get()
        ->toArray();
        $listMap = array_column($list,null,'SKUCode');
        
        //获取卡券商品信息
        $supplier = SupplierCompany::instance()->info([
            'SupplierCode'  => 'shopcoupon'
        ]);
        if( empty($supplier) ) {
            return Normal::returnCode(Normal::FAIL,"卡券专用供应商未建立,供应商编码为【shopcoupon】，请联系中台管理员核对!");
        }
        $warehouse = WarehouseInfo::instance()->info([
            'SupplierID'  => $supplier['ID']
        ]);
        if( empty($warehouse) ) {
            return Normal::returnCode(Normal::FAIL,"卡券专用供应商仓库未建立,供应商编码为【shopcoupon】，请联系中台管理员核对!");
        }
        
        $warehouse_id   = $warehouse['ID'];
        $supplier_id    = $supplier['ID'];
        $main_order_id  = IdService::instance()->getOmsID();
        $sub_order_id   = IdService::instance()->getOmsID();
        $order_time     = time();
        //开始处理卡券订单
        $orderGoods = $suppplierOrderGoods = $orderItemsList = [];
        $price_total_money = '0.00';
        foreach($goods as $item) 
        {
            $goodsSku = $item['goodsSku'];
            if( empty($listMap[$goodsSku]) ) 
            {
                return Normal::returnCode(Normal::FAIL,"当前商品自编码:{$goodsSku} 不是卡券类型商品，请核对!");
            }
            
            $quantity       = $item['goodsNum'];
            $price          = $item['goodsPrice'];
            $spec_num       = $item['goodsSpecNum'];
            $batch_no       = $item['goodsBatchNo'];
            $freight        = $item['freight'];
            $goodsInfo      = $listMap[$goodsSku];
            $sku_id         = $goodsInfo['ID'];
            $barcode        = $goodsInfo['BarCode'];
            $goods_name     = $goodsInfo['Name'];
            $skucode        = $goodsInfo['SKUCode'];
            $UnitName       = $goodsInfo['UnitName'];
            $Weight         = $goodsInfo['Weight'];
            $Images         = !empty($goodsInfo['Images']) ? json_decode($goodsInfo['Images'],true) : [];
            $ImagesArr      = array_column($Images,'ImageUrl');
            $ImagesArr      = array_filter($ImagesArr);
            $ImageUrls      = json_encode($ImagesArr,JSON_UNESCAPED_UNICODE);
            
            //返回的商品明细
            $orderItemsList[] = [
                'goodsBatchNo'  => (string)$batch_no,
                'goodsSku'      => (string)$skucode,
                'goodsNum'      => (string)$quantity,
                'goodsPrice'    => (string)$price,
                'goodsSpecNum'  => (string)$spec_num,
                'startExpDate'  => (string)($item['startExpDate'] ??''),
                'endExpDate'    => (string)($item['endExpDate'] ??'')
            ];
            
            //优惠明细部分
            $discountMoney              = $item['discountMoney'];
            $discountPointMoney         = $item['discountPointMoney'];
            $discountRedEnvelopeMoney   = $item['discountRedEnvelopeMoney'];
            $discountActivityMoney      = $item['discountActivityMoney'];
            $discountCouponMoney        = $item['discountCouponMoney'];
            $discountPaywayMoney        = $item['discountPaywayMoney'];
            $discountPrecardMoney       = $item['discountPrecardMoney'];
            $discountPoints             = $item['discountPoints'];
            $totalPrice                 = bcmul((string)$price,(string)$quantity,2);
            
            $price_total_money          = bcadd((string)$price_total_money,(string)$totalPrice,2);
            
            //主订单商品
            $orderGoods[] = [
                'id'                    => IdService::instance()->getOmsID(),
                'order_id'              => $main_order_id,
                'bid'                   => $bid,
                'goods_id'              => $sku_id,
                'goods_t_class_id'      => $goodsInfo['ThirdClassificationID'],
                'name'                  => $goods_name,
                'barcode'               => $barcode,
                'skucode'               => $skucode,
                'image'                 => $ImageUrls,
                'extra_image'           => $ImageUrls,
                'price'                 => $price,
                'quantity'              => $quantity,
                'spec_num'              => $spec_num,
                'spec_name'             => $spec_num.$UnitName,
                'total'                 => $totalPrice,
                'tax'                   => '0.00',
                'freight'               => $freight,
                'costprice'             => $price,
                'settlement_price'      => $price,
                'store_id'              => $warehouse_id,
                'batch_no'              => $batch_no,
                'stock_id'              => 0,
                'cd'                    => $order_time,
            ];
            
            //子订单商品
            $suppplierOrderGoods[] = [
                'id'                        		=> IdService::instance()->getOmsID(),
                'order_id'                          => $sub_order_id,
                'bid'                       		=> $bid,
                'goods_id'                  		=> $sku_id,
                'goods_name'                		=> $goods_name,
                'barcode'                   		=> $barcode,
                'skucode'                   		=> $skucode,
                'supplier_skuid'            		=> 0,
                'supplier_skucode'          		=> 0,
                'supplier_store_code'       		=> 0,
                'supplier_store_id'         		=> 0,
                'supplier_goods_type'       		=> 0,
                'supplier_store_parameters' 		=> '[]',
                'is_supplier_combine_skuid' 		=> 0,
                'goods_type'                		=> 0,
                'image'                     		=> $ImageUrls,
                'quantity'                  		=> $quantity,
                'spec_num'                  		=> $spec_num,
                'spec_name'                 		=> $spec_num.$UnitName,
                'weight'                    		=> $Weight,                          //重量单位g
                'total'                     		=> $totalPrice,                 	 //商品总价
                'price'                     		=> $price,							 //商品单价
                'costprice'                 		=> $price,             	             //供应商成本价
                'tax'                       		=> '0.00',                           //单商品总税费
                'tax_rate'                  		=> '0.00',                           //商品税率
                'has_rate'                  		=> 1,
                'channel_has_rate'          		=> $binfo['user_tax_mode'],           //是否用户设置含税
                'is_free_postfee'           		=> 1,                                 //是否包邮
                'freight'                   		=> $freight,                          //商品运费
                'discount_money'                    => $discountMoney,                    //商品总优惠金额
                'discount_point_money'              => $discountPointMoney,               //商品积分优惠金额
                'discount_red_envelope_money'       => $discountRedEnvelopeMoney,         //商品红包优惠金额
                'discount_activity_money'           => $discountActivityMoney,            //商品活动优惠金额
                'discount_coupon_money'             => $discountCouponMoney,              //商品优惠卡券金额
                'discount_payway_money'             => $discountPaywayMoney,              //商品支付方式优惠金额
                'discount_precard_money'            => $discountPrecardMoney,             //商品预付卡支付金额
                'discount_points'                   => $discountPoints,                   //抵扣积分
                'settlement_price'          		=> $price,                            //商户结算价格
                'store_id'                  		=> $warehouse_id,                     //仓库ID
                'batch_no'                  		=> $batch_no,	                      //批次号
                'stock_id'                  		=> 0,                                 //库存ID
                'cd'                        		=> $order_time,						  //创建时间
            ];
        }
        
        //运费
        $deliver_money      = !empty($placeOrderInfo['freight'])        ? $placeOrderInfo['freight']        : '0.00';
        $discountMoney      = !empty($placeOrderInfo['discountMoney'])  ? $placeOrderInfo['discountMoney']  : '0.00';
        $real_total_money   = !empty($placeOrderInfo['orderMoney'])     ? $placeOrderInfo['orderMoney']     : '0.00';
        $order_total_money  = bcadd((string)$real_total_money,(string)$discountMoney,2);
        
        //优惠明细
        $discountPointMoney         = $placeOrderInfo['discountPointMoney'];
        $discountRedEnvelopeMoney   = $placeOrderInfo['discountRedEnvelopeMoney'];
        $discountActivityMoney      = $placeOrderInfo['discountActivityMoney'];
        $discountCouponMoney        = $placeOrderInfo['discountCouponMoney'];
        $discountPaywayMoney        = $placeOrderInfo['discountPaywayMoney'];
        $discountPrecardMoney       = $placeOrderInfo['orderPrecardBalanceMoney'];
        $discountPoints             = $placeOrderInfo['orderPoints'];
        
        //订单号
        $orderSn = (string)$placeOrderInfo['orderSn'];
        $order_info = Order::instance()->info(['bid'=>$bid,'order_sn'=>$orderSn],['id']);
        if( !empty($order_info) ) {
            return Normal::returnCode('100000',"当前订单号【{$orderSn}】不能重复提交-2");
        }
        
        //组装主订单
        $main_order = [
            'id'                    => $main_order_id,
            'order_type'            => 2,                                   //订单类型
            'order_from_type'       => 0,                                   //订单来源类型
            'order_sn'              => $orderSn,                            //商户订单号
            'order_source'          => $placeOrderInfo['orderSource'],      //订单来源
            'bid'                   => $binfo['bid'],                       //商户ID
            'buyer_realname'        => $placeOrderInfo['buyerRealName'],    //下单人
            'buyer_phone'           => $placeOrderInfo['buyerPhone'],       //下单人电话
            'buyer_idcard'          => $placeOrderInfo['buyerIdCard'],      //下单人身份证号
            'receive_name'          => $placeOrderInfo['receiveName'],      //收货人姓名
            'recveive_phone'        => $placeOrderInfo['recveivePhone'],    //收货人电话
            'province'              => $placeOrderInfo['province'],         //省
            'city'                  => $placeOrderInfo['city'],             //市
            'district'              => $placeOrderInfo['district'],         //区
            'receive_address'       => $placeOrderInfo['receiveAddress'],   //收货地址
            'discount_money'        => $placeOrderInfo['discountMoney'],    //优惠金额
            'money'                 => $price_total_money,					//订单商品金额
            'goodstax'              => 0.00,						        //商品税费
            'deliver_money'         => $deliver_money,                      //运费
            'freight'               => $deliver_money,                      //运费
            'freighttax'            => '0.00',                              //运费税
            'tax'                   => '0.00',                              //总税费
            'totalmoney'            => $order_total_money,                  //总金额
            'order_costprice'       => $price_total_money,                  //订单总成本
            'settlementmoney'       => $price_total_money,                  //结算总价
            'remark'                => $placeOrderInfo['orderRemarks'],     //订单备注
            'cd'                    => $order_time,                              //创建时间
        ];
        
        //获取身份证信息
        $cardInfo = getIdCardInfo($placeOrderInfo['buyerIdCard']);
        //组装子订单
        $sub_order = [
            'id'                        => $sub_order_id,
            'order_sn'              	=> $orderSn,
            'supplier_psn'          	=> $orderSn,
            'supplier_csn'          	=> $orderSn,
            'supplier_dsn'              => $orderSn,
            'company_id'                => $supplier_id,
            'bid'                   	=> $bid,
            'order_type'                => 0,
            'order_commodity_type'      => 0,
            'order_trade_type'          => $placeOrderInfo['orderTradeType'],
            'company_type'              => 1,
            'is_channel'                => 1,
            'store_id'              	=> $warehouse_id,
            'buyer_realname'        	=> $placeOrderInfo['buyerRealName'],			//下单人
            'buyer_phone'           	=> $placeOrderInfo['buyerPhone'],				//下单人电话
            'buyer_idcard'          	=> $placeOrderInfo['buyerIdCard'],				//下单人身份证号
            'buyer_sex'                 => $cardInfo['sex'],//性别
            'buyer_age'                 => $cardInfo['age'],//年龄
            'buyer_id_volid'            => $cardInfo['is_volid'],//是否有效
            'receive_name'          	=> $placeOrderInfo['receiveName'],				//收货人姓名
            'recveive_phone'        	=> $placeOrderInfo['recveivePhone'],			//收货人电话
            'province'              	=> $placeOrderInfo['province'],					//省
            'city'                  	=> $placeOrderInfo['city'],						//市
            'district'              	=> $placeOrderInfo['district'],					//区
            'receive_address'       	=> $placeOrderInfo['receiveAddress'],			//收货地址
            'order_money'           	=> $order_total_money,		                    //订单金额
            'goods_money'           	=> $price_total_money,                          //商品金额
            'deliver_money'         	=> $deliver_money,                             //运费金额
            'discount_money'        	=> $discountMoney,                             //优惠金额
            'total_money'           	=> $order_total_money,                         //订单金额
            'invoice_money'         	=> '0.00',                                     //发票金额
            'real_total_money'      	=> $real_total_money,                          //实付金额
            'costprice'                 => $price_total_money,                          //供应商成本价
            'settlement_total_money'    => $price_total_money,                          //商户结算价格
            'order_remark'          	=> $placeOrderInfo['orderRemarks'],             //订单备注
            'order_source'              => $placeOrderInfo['orderSource'],              //订单来源
            'origin_order_id'           => 0,            //原始订单id
            'origin_supplier_dsn'       => 0,            //原始订单号
            'is_split_order'            => 0,           //是否拆单
            'tax'                   	=> '0.00',                              	//订单总税费
            'cd'                    	=> $order_time,
            'is_order_declare'          => 0,
            'is_pay_declare'            => 0,
            'is_child_system'           => 0,
            'is_top_system'             => 1,//是否属于最后一级云仓
            'is_query_express'          => 0,
            'total_template_delivery'   => 0,//总的模板运费
            'delivery_template_info'    => '',//地区运费模板
            'is_seckill'                => 0,
            'is_supplier_settlement'    => 0,
            'is_channel_settlement'     => 0,
            'is_encrypt_order'          => 0
        ];
        
        //订单其它消费金额扩展表
        $supplierAmountExtra = [
            'order_id'                      => $sub_order_id,
            'discount_money'                => $discountMoney,
            'discount_points_money'         => $discountPointMoney,
            'discount_red_envelope_money'   => $discountRedEnvelopeMoney,
            'discount_activity_money'       => $discountActivityMoney,
            'discount_activity_name'        => $placeOrderInfo['discountActivityName'] ?? '',
            'discount_coupon_money'         => $discountCouponMoney,
            'discount_coupon_names'         => $placeOrderInfo['discountCouponNames'] ?? '',
            'discount_payway_money'         => $discountPaywayMoney,
            'discount_red_envelope_name'    => $placeOrderInfo['discountRedEnvelopeName'] ?? '',
            'order_pre_sale_stage'          => $placeOrderInfo['orderPreSaleStage'] ?? '0',
            'order_precard_balance_money'   => $discountPrecardMoney,
            'order_points'                  => $discountPoints,
            'cd'                            => $order_time,
        ];
        
        //返回创建订单结果集
        $orderItems = [
            "orderSn"               => $orderSn,
            "orderNo"               => $orderSn,
            "orderStatus"           => 0,
            "isPay"                 => false,
            "goodsMoney"            => $price_total_money,
            "deliverMoney"          => $deliver_money,
            "totalTemplateDelivery" => 0,
            "discountMoney"         => $discountMoney,
            "totalMoney"            => $order_total_money,
            "invoiceMoney"          => 0.00,
            "realTotalMoney"        => $real_total_money,
            "goods_items"           => $orderItemsList
        ];
        
        
        try {
        
            OrderSupplier::instance()->startTrans();
            $resId = Order::instance()->insert($main_order);
            if( !$resId) {
                OrderSupplier::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"创建订单失败-1");
            }
            
            $resId = OrderGoods::instance()->insert($orderGoods);
            if( !$resId) {
                OrderSupplier::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"创建订单失败-2");
            }
            
            $resId = OrderSupplier::instance()->insert($sub_order);
            if( !$resId) {
                OrderSupplier::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"创建订单失败-3");
            }
        
            $resId = OrderSupplierGoods::instance()->insert($suppplierOrderGoods);
            if( !$resId) {
                OrderSupplier::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,"创建订单失败-4");
            }
            
            //写入资金扩展表数据
            OrderSupplierAmountExtra::instance()->insert($supplierAmountExtra);
            OrderSupplier::instance()->commit();
            return Normal::returnCode(Normal::SUC,"创建订单成功",[
                "orderItems" => [
                    $orderItems
                ]
            ]);
        } catch ( \Throwable $e ) {
            OrderSupplier::instance()->rollback();
            return Normal::returnCode($e->getCode(),$e->getMessage());
        }
    }
}